package model

import (
	"blog/app/common"
	"blog/app/utils"
	"log"
	"fmt"
)

type ArticleTag struct {
	ID        uint64 `json:"id"`
	ArticleID uint64 `json:"article_id"`
	TagID     uint64 `json:"tag_id"`
}

// 根据标签id查询文章ID array
func (t *ArticleTag) GetArticleIdArr() []interface{} {
	sql := "select distinct article_id from article_tag where tag_id=?"
	rows, err := common.DB.Query(sql, t.TagID)
	if utils.CheckErr(err) {
		return nil
	}
	var articleIds []interface{}
	for rows.Next() {
		var articleId interface{}
		err := rows.Scan(&articleId)
		if err != nil {
			return nil
		}
		articleIds = append(articleIds, articleId)
	}
	rows.Close()
	return articleIds
}

func (t *ArticleTag) BatchInsert(ids []interface{}) bool {
	if len(ids) == 0{
		return false
	}
	log.Println("article_tag model BatchInsert")
	sql := "insert into article_tag (article_id,tag_id) values"
	for i := 0; i < len(ids); {
		sql += "(?,?),"
		i += 2
	}
	sql = sql[:len(sql)-1]
	fmt.Println(sql)
	fmt.Println(ids)
	rs, err := common.DB.Exec(sql, ids...)
	if utils.CheckErr(err) {
		return false
	}
	_, err = rs.LastInsertId()
	if utils.CheckErr(err) {
		return false
	}
	return true
}

func (t *ArticleTag) DeleteOne() bool {
	sql := "delete from article_tag where article_id=?"
	rs, err := common.DB.Exec(sql, t.ArticleID)
	if utils.CheckErr(err) {
		return false
	}
	_, err = rs.RowsAffected()
	if utils.CheckErr(err) {
		return false
	}
	return true
}
